<style scoped>
.ms-tree-space {
    position: relative;
    top: 1px;
    display: inline-block;
    font-family: 'Glyphicons Halflings';
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: 18px;
    height: 14px;
}

.ms-tree-space::before {
    content: ""
}


</style>


<template>
    <div style='width:100%;border:1px solid #dfe6ec' class="tree">
        <div v-if="showTemplate==true">
            <el-table   :data="data" border style="width: 100%" :row-style="showTr" :cell-style="cellcenter" @row-click="rowClick" ref="treeTable" highlight-current-row>
                <el-table-column v-for="(column, index) in columns" :min-width="column.width" :key="column.dataIndex" :label="column.text">
                    <template slot-scope="scope">
                        <span v-if="spaceIconShow(index)" v-for="(space, levelIndex) in scope.row._level" :key="levelIndex" class="ms-tree-space"></span>
                        <Button type="text" class="boult" v-if="toggleIconShow(index,scope.row)" @click="toggle(scope.$index)" style="padding:6px 20px;"> 
                            <span style="color:#F2B217;font-size:17px;">
                                <Icon type="folder"></Icon>
                            </span>
                        </Button>
                        <span style="color:#999999;margin-left:20px;font-size:17px;" v-if="scope.row.type!=0">
                            <Icon type="document" v-if="column.dataIndex!='size'"></Icon>
                            <span  class="ms-tree-space"></span>
                        </span>   
                        <span>
                            {{scope.row[column.dataIndex]}}
                        </span> 
                    </template> 
                </el-table-column>
                <el-table-column label="操作" v-if="treeType === 'normal'" min-width="10%" >
                    <template slot-scope="scope">
                        <div style="width:100%;text-align:center;">
                            <Button style="padding:2px 18px;font-size:12px;background:#4578ad;" type="primary" v-if="scope.row.type=='fastq'||scope.row.type=='vcf'||scope.row.type=='fq'" size="small" @click="copy(scope.row)">
                                添加
                            </Button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin:10px;">
                <Button type="primary" @click="templateIsFalse" style="float:right;margin-top:10px; padding:2px 18px;" >返回</Button>
            </div>
        </div>
        
        <div v-else>
            <el-table :data="cloneData" :span-method="objectSpanMethod"  border style="width: 100%;" ref="treeTableTwo" class="tree-list-table" row-style='line-heigth:40px;'>
                <el-table-column prop="fileType" label="文件类型" width="180" >
                    
                    <template slot-scope="scope" >
                        {{scope.row.fileType}}
                        <!-- <span @click="addRow(scope.row,scope.$index)" style="float: right;margin-right: 10px;"><i class="el-icon-plus" style="color:#4578ad"></i></span> -->
                    </template>
                </el-table-column>
                <el-table-column prop="filename" label="文件名称" min-width="50%"></el-table-column>
                <el-table-column prop="size" label="文件大小" min-width="20%"></el-table-column>
                <el-table-column label="删除" min-width="10%" >
                    <template slot-scope="scope">
                        <div style="width:100%;text-align:center;line-height:40px">
                            <Button style="padding:4px 12px;font-size:12px;background:#4578ad;margin-right:5px" type="primary" size="small" @click="deleteFile(scope.row,scope.$index)">
                                删除
                            </Button>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="选择" min-width="10%" >
                    <template slot-scope="scope">
                        <div style="width:100%;text-align:center;line-height:40px">
                            <Button style="padding:4px 12px;font-size:12px;background:#4578ad;" type="primary" size="small" @click="select(scope.row,scope.$index)">
                                选择
                            </Button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose">
            <span>这是一段信息</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
        




    </div>
</template>
<script>
import Utils from '../utils/index.js'
import { data} from 'api/index.js'
import {getCookie} from '@/common/js/cookie.js'
//  import Vue from 'vue'
export default {
    name: 'tree-grid',
    props: {
        // 该属性是确认父组件传过来的数据是否已经是树形结构了，如果是，则不需要进行树形格式化
        treeStructure: {
            type: Boolean,
            default: function() {
                return false
            }
        },
        // 这是相应的字段展示
        columns: {
            type: Array,
            default: function() {
                return []
            }
        },
        // 这是数据源
        dataSource: {
            type: Array,
            default: function() {
                return []
            }
        },
        // 这个作用是根据自己需求来的，比如在操作中涉及相关按钮编辑，删除等，需要向服务端发送请求，则可以把url传过来
        requestUrl: {
            type: String,
            default: function() {
                return ''
            }
        },
        // 这个是是否展示操作列
        treeType: {
            type: String,
            default: function() {
                return 'normal'
            }
        },
        // 是否默认展开所有树
        defaultExpandAll: {
            type: Boolean,
            default: function() {
                return false
            }
        },
        //分析类型
        analysisType:{
            type: String,
            default: function() {
                return '0'
            }
        }
    },
    data() {
        return {
            sids:"",
            showTemplate:false,
            copyname:[],  //已添加文件
            currentSelect:{},//当前选择行
            cloneData:[],
            spanArr:[],
            pos:0,
            dialogVisible: false,
            tableData:[],
            uploadType:0,
            fileGroupId:"",
            requestUrlData:'',
        }
    },
    computed: {
        // 格式化数据源
        data: function() {
            let me = this
            if (me.treeStructure) {
                let data = Utils.MSDataTransfer.treeToArray(me.dataSource, null, null, me.defaultExpandAll)
                console.log(data)
                return data
            }
            return me.dataSource
        }
    },
    mounted(){
        // this.getFileData(this.requestUrlData)
        console.log(this.requestUrl)
    },
    created() {
        if(this.analysisType == 0){
            this.tableData =[
                {
                    "filename":"",
                    "size":"",
                    "path":"",
                    "fileType":"遗传病",
                    "status":"1",
                    "children":null
                }
            ]
        }else{
            this.tableData = [
                {
                    "filename":"",
                    "size":"",
                    "path":"",
                    "fileType":"肿瘤Tumor",
                    "status":"1",
                    "children":null
                },
                {
                    "filename":"",
                    "size":"",
                    "path":"",
                    "fileType":"肿瘤Normal",
                    "status":"1",
                    "children":null
                },
            ]
        }
        this.FormatData(this.tableData);
    },
    // mounted(){
    //     this.sids=this.$refs.treeTableTwo.$parent.requestUrl; 
    //     let sampleid = this.requestUrl
    //     console.log(sampleid)
    //     data.UploadFileGroupMes(sampleid).then((data) => {
    //         console.log(data)
    //     })
    // },
    watch:{
        analysisType(newValue,oldValue){
            if(this.analysisType == 0){
                this.tableData =[
                    {
                        "filename":"",
                        "size":"",
                        "path":"",
                        "fileType":"遗传病",
                        "status":"1",
                        "children":null
                    }
                ]
            }else{
                this.tableData = [
                    {
                        "filename":"",
                        "size":"",
                        "path":"",
                        "fileType":"肿瘤Tumor",
                        "status":"1",
                        "children":null
                    },
                    {
                        "filename":"",
                        "size":"",
                        "path":"",
                        "fileType":"肿瘤Normal",
                        "status":"1",
                        "children":null
                    },
                ]
            }
            this.FormatData(this.tableData);
        },
        requestUrl(newValue,oldValue){
            this.requestUrlData = newValue
            this.getFileData(newValue) 
        }
    },
    methods: {
        //删除单个文件
        deleteFile(cos,row){
            console.log(cos,row)
            let arr = []

            arr.push(cos.fileid)
            console.log(arr)
            let obj = {
               idList: arr
            }
            data.DeleteFiled(obj).then((data) => {
                console.log(data)
                if(data.msg == 'Pipeline正在执行'){
                    this.$Message.error(data.msg+'请稍后删除');
                }else{
                    this.getFileData(this.requestUrlData)
                }
                
            })
        },
        //初始化数据
        getFileData(newValue){
            data.UploadFileGroupMes(newValue).then((data) => {
                console.log(data.data)
                if(data.data){
                    let arr = []
                    data.data.filter( o => {
                        if(o.analysisType == 'Somtic' && o.fileGroupType == 'Normal'){
                            o.fileModel.filter( file => {
                                file.fileType = '肿瘤Normal'
                                arr.push(file)
                            })
                        }else if(o.analysisType == 'Somtic' && o.fileGroupType == 'Tumor'){
                            o.fileModel.filter( file => {
                                file.fileType = '肿瘤Tumor'
                                arr.push(file)
                            })
                        }else{
                            o.fileModel.filter( file => {
                                file.fileType = '遗传病'
                                arr.push(file)
                            })
                        }
                    })
                    if(arr.length > 0){
                        if(data.data[0].analysisType == 'Somtic'){
                            if(arr.length == 1){
                                if(arr[0].fileType == '肿瘤Tumor'){
                                    arr.push( {
                                        "filename":"",
                                        "size":"",
                                        "path":"",
                                        "fileType":"肿瘤Normal",
                                        "status":"1",
                                        "children":null
                                    })
                                }else{
                                    arr.push( {
                                        "filename":"",
                                        "size":"",
                                        "path":"",
                                        "fileType":"肿瘤Tumor",
                                        "status":"1",
                                        "children":null
                                    })
                                }
                            }else if(arr.length == 2){
                                if(arr[0].fileType == '肿瘤Tumor' && arr[1].fileType == '肿瘤Tumor'){
                                    arr.push( {
                                        "filename":"",
                                        "size":"",
                                        "path":"",
                                        "fileType":"肿瘤Normal",
                                        "status":"1",
                                        "children":null
                                    })
                                }else if(arr[0].fileType == '肿瘤Normal' && arr[1].fileType == '肿瘤Normal'){
                                    arr.push( {
                                        "filename":"",
                                        "size":"",
                                        "path":"",
                                        "fileType":"肿瘤Tumor",
                                        "status":"1",
                                        "children":null
                                    })
                                }
                            }
                        }
                        console.log(arr)
                        this.cloneData = arr
                        this.FormatData(this.cloneData);
                    }
                }else{
                    this.FormatData(this.tableData);
                }
                
                
            })
        },
        //添加一行
        addRow(row,index){
            console.log(row,index)
            // let oldTable = this.tableData;
            // var obj={
            //     "filename":"",
            //     "size":"",
            //     "path":"",
            //     "fileType":row.fileType,
            //     "status":"1",
            //     "children":null
            // }
            // oldTable.push(obj)
            // this.FormatData(oldTable);
        },
        //合并单元格规则
        objectSpanMethod({ row, column, rowIndex, columnIndex }){
            if (columnIndex === 0 ||  columnIndex === 4) {
                const _row = this.spanArr[rowIndex];
                return {
                    rowspan: _row,
                    colspan: 1
                }
            }
        }, 
        templateIsFalse() {
            this.showTemplate = false
            this.getFileData(this.requestUrlData)
        },
        getSpanArr(data) {　
            this.spanArr = [];
            this.pos = 0;
            for (var i = 0; i < data.length; i++) {
                if (i === 0) {
                    this.spanArr.push(1);
                    this.pos = 0;
                } else {
                // 判断当前元素与上一个元素是否相同
                    if (data[i].fileType === data[i - 1].fileType) {
                        this.spanArr[this.pos] += 1;
                        this.spanArr.push(0);
                    } else {
                        this.spanArr.push(1);
                        this.pos = i;
                    }
                }
            }
        },
        FormatData(data){
            let arr = [],
                arr1 = [],
                arr2 = [];
                // data.filter(o => {
                //     if(o.type == '遗传病'){
                //         arr.push(o)
                //     }else if(o.type == '肿瘤T'){
                //         arr1.push(o)
                //     }else if(o.type == '肿瘤N'){
                //         arr2.push(o)    
                //     }
                // })
                for (var i = 0;i<data.length; i++){
                    if(data[i].fileType == '遗传病'){
                        arr.push(data[i])
                    }else if(data[i].fileType == '肿瘤Tumor'){
                        arr1.push(data[i])
                    }else if(data[i].fileType == '肿瘤Normal'){
                        arr2.push(data[i])    
                    }
                }
                var data = [...arr,...arr1,...arr2];
                this.getSpanArr(data);
                this.cloneData = data;
        },
        select(row,index){
            console.log(row)
            console.log(this.analysisType)
            this.sids=this.$refs.treeTableTwo.$parent.requestUrl;
            let that = this
            this.showTemplate = true
            this.currentSelect = row
            if(row.fileType == '遗传病' || row.fileType == '肿瘤Tumor'){
                this.uploadType = 1
            }else if(row.fileType == '肿瘤Normal'){
                this.uploadType = 0
            }
            let obj = {
                fileGroupType:this.uploadType,
                fileGroupName:"test",
                analysisType:this.analysisType,
                sampleId:this.sids
            }
            data.UploadFileGroups(obj).then((data) => {
                this.fileGroupId = data.data.id
            })
        },
        copy(row){  
            this.sids=this.$refs.treeTable.$parent.requestUrl;
            let fileGroupIdCopy = this.fileGroupId
            let obj={
                "path":row.path,
                "fileName":row.filename,
                "userId":getCookie("userid"),
                "sampleid":this.sids,
                "productId":this.$store.state.productId,
                "fileGroupId":fileGroupIdCopy
            }
            let flag=true;
            if(this.copyname.length==1 && this.copyname[0]==row.filename){
                // this.$Message.error({
                //     content:'<div class="prompt">该文件已添加</div>',
                //     duration: 2
                // })
                this.$Message.error(data.msg)
            }else{
                if(flag){
                    flag=false;
                    console.log(obj)
                    data.addFastq(obj).then((data)=>{
                        if(data.returnCode=="0" || data.returnCode==0){
                            // this.$Message.success({
                            //     content:'<div class="prompt">'+data.msg+'</div>',
                            //     duration: 2
                            // })
                            this.$Message.success(data.msg)
                            this.copyname.push(row.filename)
                            this.$emit('s')
                        }else {
                            this.$Message.error(data.msg);
                        }
                        flag=true;
                    })
                }
            }
        },
        setRow(row) {
            this.$refs.treeTable.setCurrentRow(row)
        },
        rowClick(row, event, column) {
            this.$emit("row-click", row, event, column)
        },
        // tableBtnClick(name, row) {
        //     this.$emit("operate", name, row)
        // },
        //文件大小行，居中显示
        cellcenter({row, column, rowIndex, columnIndex}){
            // console.log(columnIndex)
            if(columnIndex==1){
                return 'text-align:center;'
            }
        },
        // 显示行
        showTr: function({row, index}) {
            let show = (row._parent ? (row._parent._expanded && row._parent._show) : true)
            row._show = show
            return show ? '' : 'display:none;'
        },
        // 展开下级
        toggle: function(trIndex) {
            let me = this
            let record = me.data[trIndex]
            record._expanded = !record._expanded
            this.getChild(trIndex)
        },
        //获取下一级数据
        getChild:function(trIndex){
            let me = this
            let record = me.data[trIndex]
            if(this.$store.state.treeGrid==1){
                this._getLocalDataList(record);
            }else if(this.$store.state.treeGrid==2){
                this._getServerDataList(record);
            }
            
        },
        // 显示层级关系的空格和图标
        spaceIconShow(index) {
            let me = this
            if (me.treeStructure && index === 0) {
                return true
            }
            return false
        },
        // 点击展开和关闭的时候，图标的切换
        toggleIconShow(index, record) {
            let me = this
            if (me.treeStructure && record.status==0 && index===0) {
                return true
            }
            return false
        },
        // 获得本地/opt/NfsDir/PublicDir/demo/
        _getLocalDataList(record) {
            let obj={
                "path":record.path,
                "userId":getCookie("userid"),
                "productId":this.$store.state.productId,
                "type":"2"
            }
            data.getSingleForldList(obj).then((data)=>{
                if(data.returnCode==0 || data.returnCode==200){
                    if(M.isArray(data.data)) {
                        record.children=data.data;
                    }
                }else if(data.returnCode==422 || data.returnCode==204){
                    this.$router.push('/login')
                }else{
                    this.$Message.error(data.msg)
                }
                
            }).catch((error)=>{

            })
        },
        _getServerDataList(record) {
            let obj={
                "path":record.path,
                "userId":getCookie("userid"),
                "productId":this.$store.state.productId,
                "type":"2"
            }
            data.getSingleForldList(obj).then((data)=>{
                    // console.log(data)
                if(data.returnCode==0 || data.returnCode==200){
                    if(M.isArray(data.data)) {
                        record.children=data.data;
                    }
                }else if(data.returnCode==422 || data.returnCode==204){
                    this.$router.push('/login')
                }else{
                    this.$Message.error(data.msg)
                }
            }).catch((error)=>{

            })
        }
    }
}
</script>

